package ignoreruleoperationlogic

import (
	"context"

	"dfx_cmdb/cmdb-blacklist-rpc/internal/svc"
	cmdb_blacklist_rpc "dfx_cmdb/cmdb-blacklist-rpc/types/cmdb-blacklist-rpc"
	cmdbblacklist "dfx_cmdb/models/cmdb-blacklist"

	"github.com/zeromicro/go-zero/core/logx"
)

type InsertIgnoreRuleLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewInsertIgnoreRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *InsertIgnoreRuleLogic {
	return &InsertIgnoreRuleLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 添加忽略规则
func (l *InsertIgnoreRuleLogic) InsertIgnoreRule(in *cmdb_blacklist_rpc.InsertIgnoreRuleRequest) (*cmdb_blacklist_rpc.PublicResponse, error) {
	// 参数验证
	if in.IgnoreType == "" {
		return &cmdb_blacklist_rpc.PublicResponse{
			Message: "ignore_type 不能为空",
		}, nil
	}
	if in.IgnoreVal == "" {
		return &cmdb_blacklist_rpc.PublicResponse{
			Message: "ignore_val 不能为空",
		}, nil
	}

	// 检查是否已存在相同的忽略规则
	var existingRule cmdbblacklist.BlacklistIgnoreRule
	err := l.svcCtx.PDB.Where("ignore_type = ? AND ignore_val = ?", in.IgnoreType, in.IgnoreVal).
		First(&existingRule).Error
	if err == nil {
		return &cmdb_blacklist_rpc.PublicResponse{
			Message: "该忽略规则已存在",
		}, nil
	}

	// 创建忽略规则
	rule := cmdbblacklist.BlacklistIgnoreRule{
		Enable:     &in.Enabled,
		IgnoreType: in.IgnoreType,
		IgnoreVal:  in.IgnoreVal,
	}

	if err := l.svcCtx.PDB.Create(&rule).Error; err != nil {
		l.Errorf("插入忽略规则失败: %v", err)
		return &cmdb_blacklist_rpc.PublicResponse{
			Message: "插入忽略规则失败",
		}, err
	}

	return &cmdb_blacklist_rpc.PublicResponse{
		Message: "添加忽略规则成功",
	}, nil
}
